package com.magupe.netty.im.server.boot;

import com.magupe.netty.im.server.handler.HelloServerHandlerAdapter;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * netty server 启动类
 * 
 * @author m1873
 * @since 2020-06-06
 */
public class NettyImServer {

	private static final int PORT = 7000;
	
	public static void main(String[] args) {
		int port = PORT;
		if(args != null && args.length > 0) {
			port = Integer.parseInt(args[0]);
		}
		
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
            	.group(bossGroup, workerGroup)
            	.channel(NioServerSocketChannel.class)
            	.option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
    				@Override
    				protected void initChannel(NioSocketChannel ch) throws Exception {
    					ch.pipeline().addLast(new HelloServerHandlerAdapter());
    				}
                });
            
            // Bind and start to accept incoming connections.
            ChannelFuture channelFuture = serverBootstrap.bind("192.168.0.101", port).sync(); 

            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
				@Override
				public void operationComplete(Future<? super Void> future) throws Exception {
					
				}
			});
            
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.            
            System.err.println(channelFuture.channel().localAddress());
            System.err.println(channelFuture.channel().remoteAddress());
            channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
}
